{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LweKUTqZUn4z"
      },
      "source": [
        "##### Copyright 2025 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "cellView": "form",
        "id": "vQoUR__bUlfj"
      },
      "outputs": [],
      "source": [
        "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sP8PQnz1QrcF"
      },
      "source": [
        "# Gemini API: Basic code generation\n",
        "\n",
        "This notebook demonstrates how to use prompting to perform basic code generation using the Gemini API's Python SDK. Two use cases are explored: error handling and code generation."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bxGr_x3MRA0z"
      },
      "source": [
        "<a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/prompting/Basic_Code_Generation.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" height=30/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ysy--KfNRrCq"
      },
      "source": [
        "The Gemini API can be a great tool to save you time during the development process. Tasks such as code generation, debugging, or optimization can be done with the assistance of the Gemini model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "id": "Ne-3gnXqR0hI"
      },
      "outputs": [],
      "source": [
        "%pip install -U -q \"google-genai>=1.0.0\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "eomJzCa6lb90"
      },
      "source": [
        "## Configure your API key\n",
        "\n",
        "To run the following cell, your API key must be stored it in a Colab Secret named `GOOGLE_API_KEY`. If you don't already have an API key, or you're not sure how to create a Colab Secret, see [Authentication](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Authentication.ipynb) for an example."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "id": "v-JZzORUpVR2"
      },
      "outputs": [],
      "source": [
        "from google import genai\n",
        "from google.colab import userdata\n",
        "\n",
        "GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')\n",
        "client = genai.Client(api_key=GOOGLE_API_KEY)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UsKJpRiFzrfu"
      },
      "source": [
        "Additionally, select the model you want to use from the available options below:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "id": "rpsJhVPezrKs"
      },
      "outputs": [],
      "source": [
        "MODEL_ID = \"gemini-2.5-flash-lite\"  # @param [\"gemini-2.5-flash-lite\", \"gemini-2.5-flash\", \"gemini-2.5-flash\",\"gemini-2.5-pro\",\"gemini-3-pro-preview\"] {\"allow-input\": true, \"isTemplate\": true}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yQnqEPjephXi"
      },
      "source": [
        "## Examples"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bR-OOcC6pIm5"
      },
      "source": [
        "### Error handling"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l4ywOwlb54vw"
      },
      "source": [
        "For code generation, you should prioritize accuracy over creativity.\n",
        "A temperature of 0 ensures that the generated content is deterministic,\n",
        "producing the most sensible output every time."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "id": "kVF8ZQ38Vs1P"
      },
      "outputs": [],
      "source": [
        "from google.genai import types\n",
        "\n",
        "error_handling_system_prompt =f\"\"\"\n",
        "  Your task is to explain exactly why this error occurred and how to fix it.\n",
        "\"\"\"\n",
        "\n",
        "error_handling_model_config = types.GenerateContentConfig(\n",
        "    temperature=0,\n",
        "    system_instruction=error_handling_system_prompt\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "metadata": {
        "id": "CHTdAVE0pIFf"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "Okay, let's break down this `IndexError: list index out of range` error.\n",
              "\n",
              "**What the Error Means**\n",
              "\n",
              "The error `IndexError: list index out of range` specifically tells you that you're trying to access an element in a list using an index (a number representing its position) that doesn't exist within that list.  Think of it like trying to find a page number in a book that's beyond the total number of pages.\n",
              "\n",
              "**Why the Error Occurred in this Code**\n",
              "\n",
              "1.  **`my_list = [1, 2, 3]`**: This line creates a list named `my_list` containing the numbers 1, 2, and 3.\n",
              "\n",
              "2.  **`print(my_list[3])`**: This line attempts to print the element at index 3 of `my_list`.  **Crucially, in Python (and most programming languages), list indices start at 0.**\n",
              "\n",
              "    *   Index 0 refers to the first element (which is 1).\n",
              "    *   Index 1 refers to the second element (which is 2).\n",
              "    *   Index 2 refers to the third element (which is 3).\n",
              "\n",
              "    Since `my_list` only has three elements (at indices 0, 1, and 2), there is no element at index 3.  Trying to access `my_list[3]` goes \"out of range\" of the valid indices, hence the error.\n",
              "\n",
              "**How to Fix the Error**\n",
              "\n",
              "The fix depends on what you *intended* to do.  Here are a few possibilities and their solutions:\n",
              "\n",
              "1.  **If you wanted to access the last element:**\n",
              "\n",
              "    *   You could use index 2 (because the list has 3 elements, and the last element is at index 2):\n",
              "\n",
              "        ```python\n",
              "        my_list = [1, 2, 3]\n",
              "        print(my_list[2])  # Output: 3\n",
              "        ```\n",
              "\n",
              "    *   Alternatively, you can use negative indexing.  `-1` refers to the last element, `-2` to the second-to-last, and so on:\n",
              "\n",
              "        ```python\n",
              "        my_list = [1, 2, 3]\n",
              "        print(my_list[-1])  # Output: 3\n",
              "        ```\n",
              "\n",
              "2.  **If you wanted to access an element at a specific position (e.g., the fourth element if you *thought* there were four elements):**\n",
              "\n",
              "    *   You need to make sure your list actually *has* that many elements.  You would need to add more elements to the list:\n",
              "\n",
              "        ```python\n",
              "        my_list = [1, 2, 3, 4]  # Now the list has four elements\n",
              "        print(my_list[3])  # Output: 4\n",
              "        ```\n",
              "\n",
              "3.  **If you're unsure how many elements are in the list:**\n",
              "\n",
              "    *   Use the `len()` function to find the number of elements and then adjust your index accordingly:\n",
              "\n",
              "        ```python\n",
              "        my_list = [1, 2, 3]\n",
              "        list_length = len(my_list)  # list_length will be 3\n",
              "        if list_length > 3:  # Check if index 3 is valid\n",
              "            print(my_list[3])\n",
              "        else:\n",
              "            print(\"Index 3 is out of range for this list.\")\n",
              "        ```\n",
              "\n",
              "**In summary:** The core problem is that you're trying to access an element at an index that doesn't exist in your list.  Carefully examine your code to determine the correct index you want to use or to ensure your list has the necessary number of elements.  Remember that list indices start at 0.\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "execution_count": 12,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from IPython.display import Markdown\n",
        "\n",
        "error_message = \"\"\"\n",
        "    1 my_list = [1,2,3]\n",
        "  ----> 2 print(my_list[3])\n",
        "\n",
        "  IndexError: list index out of range\n",
        "\"\"\"\n",
        "\n",
        "error_prompt = f\"\"\"\n",
        "  You've encountered the following error message:\n",
        "  Error Message: {error_message}\n",
        "\"\"\"\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=error_prompt,\n",
        "    config=error_handling_model_config\n",
        ")\n",
        "\n",
        "Markdown(response.text)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kTDi8WyDqQRf"
      },
      "source": [
        "### Code generation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "metadata": {
        "id": "1T1QSzjVVvE_"
      },
      "outputs": [],
      "source": [
        "code_generation_system_prompt = f\"\"\"\n",
        "  You are a coding assistant. Your task is to generate a code snippet that\n",
        "  accomplishes a specific goal. The code snippet must be concise, efficient,\n",
        "  and well-commented for clarity. Consider any constraints or requirements\n",
        "  provided for the task.\n",
        "\n",
        "  If the task does not specify a programming language, default to Python.\n",
        "\"\"\"\n",
        "\n",
        "code_generation_model_config = types.GenerateContentConfig(\n",
        "    temperature= 0,\n",
        "    system_instruction=code_generation_system_prompt\n",
        "  )"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {
        "id": "8KVpzExDqRj2"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "```python\n",
              "import time\n",
              "\n",
              "def countdown_timer(seconds):\n",
              "    \"\"\"\n",
              "    Counts down from a specified number of seconds and prints \"Time is up!\" when finished.\n",
              "\n",
              "    Args:\n",
              "        seconds (int): The number of seconds to count down from.\n",
              "    \"\"\"\n",
              "    for i in range(seconds, 0, -1):  # Iterate from seconds down to 1\n",
              "        print(f\"{i} seconds remaining...\")\n",
              "        time.sleep(1)  # Pause for 1 second\n",
              "    print(\"Time is up!\")\n",
              "\n",
              "if __name__ == \"__main__\":\n",
              "    countdown_timer(20)  # Start a 20-second countdown\n",
              "```"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "execution_count": 14,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "code_generation_prompt = \"\"\"\n",
        "  Create a countdown timer that ticks down every second and prints\n",
        "  \"Time is up!\" after 20 seconds\n",
        "\"\"\"\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=code_generation_prompt,\n",
        "    config=code_generation_model_config\n",
        ")\n",
        "Markdown(response.text)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Z7X6pSdOMyvS"
      },
      "source": [
        "Let's check if generated code works."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {
        "id": "lOU_abTPSmZu"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "20 seconds remaining...\n",
            "19 seconds remaining...\n",
            "18 seconds remaining...\n",
            "17 seconds remaining...\n",
            "16 seconds remaining...\n",
            "15 seconds remaining...\n",
            "14 seconds remaining...\n",
            "13 seconds remaining...\n",
            "12 seconds remaining...\n",
            "11 seconds remaining...\n",
            "10 seconds remaining...\n",
            "9 seconds remaining...\n",
            "8 seconds remaining...\n",
            "7 seconds remaining...\n",
            "6 seconds remaining...\n",
            "5 seconds remaining...\n",
            "4 seconds remaining...\n",
            "3 seconds remaining...\n",
            "2 seconds remaining...\n",
            "1 seconds remaining...\n",
            "Time is up!\n"
          ]
        }
      ],
      "source": [
        "import re\n",
        "matchFound = re.search(r\"python\\n(.*?)```\", response.text, re.DOTALL)\n",
        "if matchFound:\n",
        "  code = matchFound.group(1)\n",
        "  exec(code)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AiGF8I290YzL"
      },
      "source": [
        "## Next steps\n",
        "\n",
        "Be sure to explore other examples of prompting in the repository. Try writing prompts around your own code as well using the examples in this notebook."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "Basic_Code_Generation.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
